package com.mspbots.web.security.repositories;

import com.mspbots.web.security.User;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import reactor.core.publisher.Mono;

/**
 * com.mspbots.web.security.UserRepository
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/8/30
 */
public interface UserRepository extends R2dbcRepository<User, String> {

    /**
     * get by username
     *
     * @param username user id
     * @return user model
     */
    @Query("select * from users where lower(username) = lower(:username)")
    Mono<User> findByUsername(String username);

    /**
     * get tenant last tenant user
     *
     * @param tenantId tenant id
     * @return find result user entry
     */
    @Query("select * from users where tenant_id=:tenantId and last_login is not null order by last_Login desc limit 1")
    Mono<User> findByTenantLast(Integer tenantId);

    /**
     * update users last login time.
     *
     * @param username update username
     * @return update result count
     */
    @Query("UPDATE users SET last_login = now() where lower(username) = lower(:username)")
    Mono<Integer> setLastLogin(String username);

    @Query("update users set enabled =:enabled where lower(username) = lower(:username)")
    Mono<Integer> updateEnabledByUsername(Boolean enabled, String username);
}
